package com.qiguliuxing.dts.service.base;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.qiguliuxing.dts.db.bean.DtsBrandMerchantInfo;
import com.qiguliuxing.dts.db.dao.DtsAdminMapper;
import com.qiguliuxing.dts.db.dao.DtsBrandMerchantMapper;
import com.qiguliuxing.dts.db.dao.DtsCategoryMapper;
import com.qiguliuxing.dts.db.dao.DtsMerchantWithdrawalAccountMapper;
import com.qiguliuxing.dts.db.domain.*;
import com.qiguliuxing.dts.db.domain.DtsBrandMerchant.Column;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DtsBrandService {
	@Resource
	private DtsCategoryMapper categoryMapper;

	@Resource
	private DtsMerchantWithdrawalAccountMapper withdrawalAccountMapper;

	@Resource
	private DtsMerchantWithdrawalService withdrawalService;

	@Resource
	private DtsBrandMerchantMapper brandMapper;
	private Column[] columns = new Column[] { Column.id, Column.name, Column.desc, Column.picUrl, Column.floorPrice };

	@Resource
	private DtsAdminMapper adminMapper;

	public List<DtsBrandMerchant> queryVO(int offset, int limit) {
		DtsBrandMerchantExample example = new DtsBrandMerchantExample();
		example.or().andDeletedEqualTo(false);
		example.setOrderByClause("add_time desc");
		PageHelper.startPage(offset, limit);
		return brandMapper.selectByExampleSelective(example, columns);
	}

	public int queryTotalCount() {
		DtsBrandMerchantExample example = new DtsBrandMerchantExample();
		example.or().andDeletedEqualTo(false);
		return (int) brandMapper.countByExample(example);
	}

	public DtsBrandMerchant findById(Integer id) {
		return brandMapper.selectByPrimaryKey(id);
	}

	public List<DtsBrandMerchant> querySelective(String id, String name, Integer page, Integer size, String sort,
			String order) {
		DtsBrandMerchantExample example = new DtsBrandMerchantExample();
		DtsBrandMerchantExample.Criteria criteria = example.createCriteria();

		if (!StringUtils.isEmpty(id)) {
			criteria.andIdEqualTo(Integer.valueOf(id));
		}
		if (!StringUtils.isEmpty(name)) {
			criteria.andNameLike("%" + name + "%");
		}
		criteria.andDeletedEqualTo(false);

		if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
			example.setOrderByClause(sort + " " + order);
		}

		PageHelper.startPage(page, size);
		return brandMapper.selectByExample(example);
	}

	public int updateById(DtsBrandMerchant brand) {
		brand.setUpdateTime(LocalDateTime.now());
		return brandMapper.updateByPrimaryKeySelective(brand);
	}

	public void deleteById(Integer id) {
		brandMapper.logicalDeleteByPrimaryKey(id);
	}

	public void add(DtsBrandMerchant brand) {
		brand.setAddTime(LocalDateTime.now());
		brand.setUpdateTime(LocalDateTime.now());
		brandMapper.insertSelective(brand);
	}

	public List<DtsBrandMerchant> all() {
		DtsBrandMerchantExample example = new DtsBrandMerchantExample();
		example.or().andDeletedEqualTo(false);
		return brandMapper.selectByExample(example);
	}
	
	public List<DtsBrandMerchant> getAdminBrands(Integer adminId) {
		if (adminId == null) {
			return null;
		}
		DtsBrandMerchantExample example = new DtsBrandMerchantExample();
		example.or().andDeletedEqualTo(false).andAdminIdEqualTo(adminId);
		return brandMapper.selectByExample(example);
	}

	/**
	 * 根据分类id获取分类名
	 * @param categoryId
	 * @return
	 */
	public String getBrandCategory(Integer categoryId) {
		DtsCategory dtsCategory = categoryMapper.selectByPrimaryKey(categoryId);
		return dtsCategory == null ? "综合" : dtsCategory.getName();
	}

	/**
	 * 根据品牌入驻商id 获取店铺管理员电话号码
	 * @param brandId
	 * @return
	 */
    public String getBrandMangerTelByBrandId(Integer brandId) {
		DtsBrandMerchant brand = brandMapper.selectByPrimaryKey(brandId);
		if (brand != null && brand.getAdminId()!= null) {
			return adminMapper.selectByPrimaryKey(brand.getAdminId()).getTel();
		} else {
			return null;
		}
    }

	/**
	 * 根据品牌入驻商id 获取店铺管理员邮箱地址
	 * @param brandId
	 * @return
	 */
	public String getBrandMangerMailByBrandId(Integer brandId) {
		DtsBrandMerchant brand = brandMapper.selectByPrimaryKey(brandId);
		if (brand != null && brand.getAdminId()!= null) {
			return adminMapper.selectByPrimaryKey(brand.getAdminId()).getMail();
		} else {
			return null;
		}
	}

    public Boolean checkBrandInfoImproved(Integer brandId) {
		return this.validate(brandMapper.selectByPrimaryKey(brandId));
    }

    public void updateBrandAndWithdrawalInfo(DtsBrandMerchantInfo b) {
		DtsBrandMerchant brandInfo = this.findById(b.getId());
		brandInfo.setName(b.getName());
		brandInfo.setDesc(b.getDesc());
		brandInfo.setPicUrl(b.getPicUrl());
		brandInfo.setFloorPrice(b.getFloorPrice());
		brandInfo.setCompany(b.getCompany());
		brandInfo.setAutoUpdateGood(b.getAutoUpdateGood());
		brandInfo.setDefaultCategoryId(b.getDefaultCategoryId());
		brandInfo.setDefaultPages(b.getDefaultPages());
		brandInfo.setAddPercent(b.getAddPercent());
		brandInfo.setShareUrl(b.getShareUrl());
		brandInfo.setAddress(b.getAddress());
		brandInfo.setLongitude(b.getLongitude());
		brandInfo.setLatitude(b.getLatitude());
		if(ArrayUtils.isNotEmpty(b.getFetchTimeRules())){
			brandInfo.setFetchTimeRules(b.getFetchTimeRules());
		}
		this.updateById(brandInfo);

		List<DtsMerchantWithdrawalAccount> newWithdrawAccount = b.getWithdrawAccount();
		List<DtsMerchantWithdrawalAccount> oldWithdrawAccount = withdrawalService.findByBrandId(brandInfo.getId());
		List<Integer> removeAccountIds = Lists.newArrayList();
		for (int i = 0; i < newWithdrawAccount.size(); i++) {
			if(Objects.isNull(newWithdrawAccount.get(i).getId()) && !Objects.isNull(oldWithdrawAccount.get(i).getId())){
				removeAccountIds.add(oldWithdrawAccount.get(i).getId());
			}
		}

		List<DtsMerchantWithdrawalAccount> noEmptyAccounts = b.getWithdrawAccount()
				.stream().filter((e) -> StringUtils.isNotBlank(e.getAccount()) )
				.collect(Collectors.toList());
		noEmptyAccounts.get(0).setIsDefault((byte) 1);
		noEmptyAccounts.forEach(item->{
			if(!Objects.isNull(item.getId())){
				withdrawalAccountMapper.updateByPrimaryKeySelective(item);
			}else{
				item.setBrandId(b.getId());
				withdrawalAccountMapper.insertSelective(item);
			}
		});
		removeAccountIds.forEach(id -> withdrawalAccountMapper.deleteByPrimaryKey(id) );
    }

	public Boolean validate(DtsBrandMerchant brand) {
		String name = brand.getName();
		if (StringUtils.isEmpty(name)) {
			return Boolean.FALSE;
		}

		if (StringUtils.isEmpty(brand.getPicUrl())) {
			return Boolean.FALSE;
		}

		String desc = brand.getDesc();
		if (StringUtils.isEmpty(desc)) {
			return Boolean.FALSE;
		}

		BigDecimal price = brand.getFloorPrice();
		if (price == null) {
			return Boolean.FALSE;
		}

		String address = brand.getAddress();
		if (StringUtils.isEmpty(address)) {
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}
}
